<template>
  <div class="janros" @mouseover="stop = true" @mouseleave="stop = false">
    <div
      ref="movable"
      class="movable"
      style="left: 0"
      @mousedown.prevent="onStartDrag"
      @mouseup.prevent="onStopDrag"
      @mouseleave="dragX = false"
      @mousemove="onDrag"
    >
      <div class="wirotis clearfix">
        <img src="../statics/build/images/toutiao.jpg" style="z-index: 9999;" class="fl"/>
        <ul class="clearfix fl">
          <li
            v-for="item of notices"
            :key="item.announcement_id"
            class="nodets"
          >
            <a href="#" target="_blank" @click="onClickNotice">{{ item.content }}</a>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import { getNavbarNotice } from '@/api/public'

export default {
  name: 'NavbarNotice',
  data() {
    return {
      notices: [],
      movableWidth: 0,
      interval: null,
      stop: false,
      dragX: false,
      // 只要拖动过，就给该值赋值一个数，然后倒计时归0，不为0的时候，通知的链接无法打开
      preventLink: 0,
    }
  },
  created() {
    getNavbarNotice()
      .then(({ data }) => {
        this.notices = data.data
      })
  },
  mounted() {
    this.updateMovableWidth()
    this.startScroll()
    window.t = this.$refs.movable
  },
  methods: {
    updateMovableWidth() {
      this.movableWidth = this.$refs.movable.clientWidth
    },

    startScroll() {
      this.interval = setInterval(() => {
        if (this.stop) {
          return
        }

        const el = this.$refs.movable
        let left = el.offsetLeft

        if (-left > el.clientWidth) {
          left = window.innerWidth
        } else {
          left -= 1
        }
        el.style.left = left + 'px'
      }, 17)
    },

    onDrag(e) {
      if (this.dragX !== false) {
        this.$refs.movable.style.left = (e.clientX - this.dragX) + 'px'
        this.preventLink = 0.5
      }
    },

    onStartDrag(e) {
      this.dragX = e.offsetX
      if (e.target.tagName === 'A') {
        this.dragX += e.target.offsetLeft
      }
    },

    onClickNotice(e) {
      if (this.preventLink) {
        e.preventDefault()
      }
    },

    onStopDrag(e) {
      this.dragX = false
      setTimeout(() => {
        this.preventLink = 0
      }, this.preventLink * 1000)
    },
  },
  watch: {
    notices(newValue) {
      this.$nextTick(() => {
        this.updateMovableWidth()
      })
    },
  },
  beforeDestroy() {
    clearInterval(this.interval)
  },
}
</script>

<style lang="scss">
@import '~@/statics/build/css/styles.css';
</style>

<style lang="scss" scoped>
.nodets {
  margin-right: 10px;
  display: inline-block;
}

.janros {
  background: #FAFFBD;
  overflow: hidden;
  width: 100%;
  font-size: 12px;
  line-height: 16px;
  height: 35px;
  position: relative;
  white-space: nowrap;
  user-select: none;
}

.movable {
  white-space: nowrap;
  position: absolute;
  top: 0;
  cursor: move;
}
</style>
